import cv2 as cv

methods = [cv.TM_SQDIFF_NORMED, cv.TM_CCORR_NORMED, cv.TM_CCOEFF_NORMED]


def template_match(tpl, target, method=cv.TM_CCORR_NORMED):
    # 获得模板的高宽
    th, tw = tpl.shape[:2]

    # 执行模板匹配
    # target：目标图片
    # tpl：模板图片
    # 匹配模式
    result = cv.matchTemplate(target, tpl, method)
    # 寻找矩阵(一维数组当作向量,用Mat定义) 中最小值和最大值的位置
    min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
    print('min_val:%f,max_val:%f' % (min_val, max_val), )
    if method == cv.TM_SQDIFF_NORMED:
        tl = min_loc
    else:
        tl = max_loc

    br = (tl[0] + tw, tl[1] + th)
    return tl, br

    # 绘制矩形边框，将匹配区域标注出来
    # target：目标图像
    # tl：矩形定点
    # br：举行的宽高
    # (0,0,255)：矩形边框颜色
    # 2：矩形边框大小
    # cv.rectangle(target, tl, br, (0, 0, 255), 2)
    # cv.imshow('match-' + np.str(method), target)


if __name__ == '__main__':
    images = [cv.imread('/Volumes/bakup/cloud/matrix/image/blocks/%02d.png' % (x,)) for x in range(6)]

    # 模板图片


    size = 45
    x = 0
    y = 100

    img = images[0]
    cv.rectangle(img, (0, 100), (45, 145), (0, 0, 255), 2)
    cv.imshow('template', img)

    for i in range(len(images) - 1):
        tpl = img[y:y + size, x:x + size]
        target = images[i+1]
        tl, br = template_match(tpl=tpl, target=target, method=cv.TM_CCOEFF_NORMED)

        x = tl[0]
        y = tl[1]

        cv.rectangle(target, tl, br, (0, 0, 255), 2)
        cv.imshow('match-%d' % (i,), target)

        img = images[i + 1]

    # cv.imshow('match-', tpl)
    cv.waitKey(0)
    cv.destroyAllWindows()
